package com.grm.distributed.lock.service;

import com.grm.distributed.lock.common.Result;
import com.grm.distributed.lock.mapper.ProductMapper;
import com.grm.distributed.lock.pojo.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 悲观锁 select ... for update
 */
@Slf4j
@Service
public class ProductService2 {
    @Autowired
    private ProductMapper productMapper;

    public synchronized Result sell() {
        // 1. 查询并锁定库存信息
        List<Product> list = productMapper.query("1001");
        // 2. 判断库存是否充足
        // 简单取第一个仓库的库存来进行扣减
        Product product = list.get(0);
        if (product != null && product.getCount() > 0) {
            // 3.减库存 update product set count = count - 1 where code = '1001' and count > 0;
            // code设置索引，悲观锁改为行级锁，KEY `product_code_IDX` (`code`) USING BTREE
            productMapper.sell(1L);
        }
        log.info("product current count = {}", product.getCount());
        return Result.success(product.getCount());
    }
}
